<template>
    <div class="goods-image">
    <div class="large" v-show="show" :style="[{backgroundImage:`url(${image[index]})`},bgPosition]"></div>
    <div class="middle" ref="target">
        <img :src="image[index]" alt="">
        <div class="layer" v-show="show" :style="position"></div>
    </div>
    <ul class="small">
        <li v-for = "(img,i) in image" :key ="i" :class = "{active:i === index }">
            <img @mouseenter="index = i" :src="img" alt="">
        </li>
    </ul>
  </div>
</template>

<script>
import { reactive, ref, watch } from 'vue'
import {  useMouseInElement } from '@vueuse/core'
export default {
    name:'GoodsImage',
    props:{
        image:{
            type:Array
        }
    },
    setup(){
        const index = ref(0)
        // 获取中盒子元素的坐标
        const target = ref(null)
        const {elementX,elementY,isOutside} = useMouseInElement(target)
        const show = ref(false)
        // 遮罩块的移动位置坐标
        const position = reactive({left:0,top:0})
        // 大盒子的坐标
        const bgPosition = reactive({backgroundPositionX:0,backgroundPositionY:0})
        // 根据中盒子的坐标判断遮罩块移动的坐标
        // x 轴
        // 必须监听  不监听vue获取不到
        watch([elementX,elementY,isOutside],()=>{
            if(elementX.value < 100) {position.left = 0}
        else if(elementX.value > 300) {position.left = 200}
        else position.left = elementX.value - 100
        // y 轴
        if(elementY.value < 100) {position.top = 0}
        else if(elementY.value > 300) {position.top = 200}
        else position.top = elementY.value - 100
        // 大盒子结果  注意：大盒子结果必须放在遮罩块上面，不然会覆盖，有单位px没法乘
        bgPosition.backgroundPositionX = -position.left*2 + 'px'
        bgPosition.backgroundPositionY = -position.left*2 + 'px'
        // 遮罩块结果
        position.left = position.left + 'px'
        position.top = position.top + 'px'
        // 显示隐藏
        show.value = !isOutside.value
        })

        return { index, target, show, position, bgPosition}
    }
}
</script>

<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  z-index: 500;
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
     position: relative;
    cursor: move;
    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0,0,0,.2);
      left: 0;
      top: 0;
      position: absolute;
    }
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,&.active {
        border: 2px solid @xtxColor;
      }
    }
  }
  }
</style>